package com.unnamed.collisions.editor;

import java.awt.Point;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.event.MouseWheelEvent;
import java.awt.event.MouseWheelListener;

import javax.xml.stream.events.EndDocument;

import org.lwjgl.input.Mouse;

import com.unnamed.collisions.logging.Log;

interface MouseBehaviour{
	void click(Point where, int button);
	void doubleClick(Point where, int button);
	void startDrag(Point start, int button);
	void endDrag(Point start, Point end, int button);
	void move(Point position);
	void drag(Point start, Point end);
	void wheelMoved(int delta);
}

public class MouseHandler implements MouseMotionListener,MouseListener,MouseWheelListener {
	private final static int MOVING = 0;
	private final static int DRAGGING = 1;
	private final static int SELECTING = 2;
	
	Point pressPoint;
	Point releasePoint;
	Point position;
	PolyPanel panel;
	int state;
	int clickCount;
	int pressButton;
	
	MouseBehaviour behaviour;
	
	public MouseHandler(MouseBehaviour behaviour){
		//this.panel = panel;
		position = new Point(0,0);
		pressPoint = null;
		releasePoint = null;
		state = MOVING;
		
		this.behaviour=behaviour;
	}
	
	@Override
	public void mouseClicked(MouseEvent e) {
		if(e.getClickCount()==1){
			Log.log("Click event");
			behaviour.click(releasePoint, e.getButton());
		}else{
			Log.log("Double click event");
			behaviour.doubleClick(releasePoint, e.getButton());
		}
	}

	@Override
	public void mouseEntered(MouseEvent e) {
		
	}

	@Override
	public void mouseExited(MouseEvent e) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void mousePressed(MouseEvent e) {
		Log.log("Press event");
		pressPoint = new Point(e.getX(),e.getY());
		pressButton = e.getButton();
	}
	
	@Override
	public void mouseReleased(MouseEvent e) {
		releasePoint = new Point(e.getX(),e.getY());
		if(state==MOVING){
			Log.log("Release event");
		}else if(state==DRAGGING){
			state=MOVING;
			Log.log("Drag end event");
			behaviour.endDrag(pressPoint, new Point(e.getX(), e.getY()),e.getButton());
		}
	}

	@Override
	public void mouseDragged(MouseEvent e) {
		if(state==MOVING){
			state=DRAGGING;
			Log.log("Drag begin");
			behaviour.startDrag(pressPoint, pressButton);
		}else if(state==DRAGGING){
			Log.log("Drag move");
			behaviour.drag(pressPoint, new Point(e.getX(),e.getY()));
		}
	}

	@Override
	public void mouseMoved(MouseEvent e) {
		Log.log("Move event");
		behaviour.move(new Point(e.getX(),e.getY()));
	}

	public Point getPosition(){
		return position;
	}

	@Override
	public void mouseWheelMoved(MouseWheelEvent e) {
		Log.log("Wheel event");
		behaviour.wheelMoved(e.getWheelRotation());
	}
	
	public boolean isMoving(){
		return state==MOVING;
	}
	
	public boolean isDragging(){
		return state==DRAGGING;
	}
}
